package sicnu.cs.aps.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

//    @Value("${mycache.userCacheName}")
//    private String USER_CACHE;
//    @Value("${mycache.productCacheName}")
//    private String PRODUCT_CACHE;

    //private Duration timeToLive = Duration.ZERO;
    //public void setTimeToLive(Duration timeToLive) {
    //    this.timeToLive = timeToLive;
    //}
    //@Bean
    //public CacheManager cacheManager(RedisConnectionFactory factory) {
    //    RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    //    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    //
    //    //解决查询缓存转换异常的问题
    //    ObjectMapper om = new ObjectMapper();
    //    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    //    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    //    jackson2JsonRedisSerializer.setObjectMapper(om);
    //
    //    // 配置序列化（解决乱码的问题）
    //    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    //            .entryTtl(timeToLive)
    //            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
    //            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
    //            .disableCachingNullValues();
    //
    //    return RedisCacheManager.builder(factory)
    //            .cacheDefaults(config)
    //            .build();
    //}

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
        @SuppressWarnings({"rawtypes", "unchecked"})
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

//    @Bean(value = "redisCacheManager")
//    @Primary
//    public RedisCacheManager redisCacheManager(
//            @Autowired @Qualifier("redisTemplate") RedisTemplate<String, Object> redisTemplate) {
//        RedisCacheWriter redisCacheWriter = RedisCacheWriter
//                .nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory()));
//        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
//                .defaultCacheConfig()
//                .serializeValuesWith(RedisSerializationContext.SerializationPair
//                        .fromSerializer(redisTemplate.getValueSerializer()))
//                // 默认统一过期时间为60分钟
//                .entryTtl(Duration.ofMinutes(60));
//        // 注意定义的cacheManager中可以根据cacheName 设置缓存属性
//        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration,
//                this.getRedisCacheConfigurationMap());
////        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
//    }

    /**
     * 用于单独设置过期时间
     * RedisCacheManager管理(创建、初始化)具体Cache 设置具体的cache缓存超时失效时间
     */
//    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
//        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//        redisCacheConfigurationMap.put("ich",
//                this.getRedisCacheConfigurationWithTtl(30L, ChronoUnit.MINUTES));
////        redisCacheConfigurationMap.put("ichs",
////                this.getRedisCacheConfigurationWithTtl(3L, ChronoUnit.DAYS));
//        return redisCacheConfigurationMap;
//    }
//
//    /**
//     * RedisCacheManager管理(创建、初始化)具体Cache
//     */
//    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Long time,
//                                                                      TemporalUnit timeUnit) {
//        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
//                Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
//                .defaultCacheConfig();
//        redisCacheConfiguration = redisCacheConfiguration
//                .serializeValuesWith(RedisSerializationContext.SerializationPair
//                        .fromSerializer(jackson2JsonRedisSerializer))
//                .entryTtl(Duration.of(time, timeUnit));
//        return redisCacheConfiguration;
//    }
}
